
import os

def SplitPath(p):
	a, b = os.path.split(p)
	if a == '' and b == '':
		return []
	elif a == '':
		return [b]
	elif b == '':
		if a == p:
			return [a]
		else:
			return SplitPath(a)
	else:
		r = SplitPath(a)
		r.append(b)
		return r

def RelativePath(baseDir, p):
	lb = SplitPath(baseDir)
	lp = SplitPath(p)
	name = lp.pop()
	if lb == lp:
		return name
	if lb[0] != lp[0]:
		return p
	n = min(len(lb), len(lp))
	for i in range(n):
		if lb[i] != lp[i]:
			break
	else:
		i = n
	lb = lb[i:]
	lp = lp[i:]
	rlb = ['..'] * len(lb)
	return os.path.join(*(rlb + lp + [name]))

